import md5 = require("md5");
import { Transaction } from "tiny-entity2";
import { IQueryObject } from "tiny-entity2/queryObject";
import { ApiDataContext } from "../domain/apiDataContext";
import { Account } from "../domain/models/account";
import { BaseService, QueryParamsBase } from "./baseService";

export class AccountService extends BaseService {
    GetAccountByUsername(username: string) {
        let ctx = new ApiDataContext();
        return ctx.Account.First(x => x.username == $args1, { $args1: username });
    }
    async CreateAccount(entity: Account, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new Account();
            d.ConverToEntity(entity);
            return ctx.Create(d);
        });
    }
    async UpdateAccount(entity: Account, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new Account();
            d.ConverToEntity(entity);
            return ctx.Update(d);
        });
    }
    async DeleteAccount(entity: Account, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new Account();
            d.ConverToEntity(entity);
            // ctx.Delete<User>(x=>x.name == $args1, ctx.User,  {$args1: 'ddddd'});
            return ctx.Delete(d);
        });
    }
    async GetAccountById(id: string) {
        let ctx = new ApiDataContext();
        return ctx.Account.First(x => x.id == $args1, { $args1: id });
    }
    async QueryAccount(params: AccountQueryParams) {
        let q = this.GetQueryAccountCtx(params);
        let total = await q.Count();

        let q2 = this.GetQueryAccountCtx(params);
        if (params.countOfPage && params.pageIndex) {
            q2 = q2.Take(params.countOfPage).Skip(params.pageIndex - 1) as any;
        }
        let list = await q2.ToList();

        return {
            total,
            list
        };
    }

    private GetQueryAccountCtx(params: AccountQueryParams) {
        let ctx = new ApiDataContext();
        let q = ctx.Account as IQueryObject<Account>;
        q = q.Where(x => x.isDelete == $args1, { $args1: false });
        if (params) {
            if (params.username) {
                q = q.Where(x => x.username == $args1, { $args1: params.username });
            }
            if (params.password) {
                q = q.Where(x => x.password == $args1, { $args1: params.password });
            }
            if (params.linkVerifyMode) {
                q = q.Where(x => x.verifyMode.indexOf($args1) > -1, { $args1: params.linkVerifyMode });
            }
        }
        return q;
    }
}
export interface AccountQueryParams extends QueryParamsBase {
    username?: string;
    password?: string;
    linkVerifyMode?: string;
}